//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by HM on 16/5/22.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD
//偏好设置保存的key
private let userInfoKey = "com.itheima.userInfoKey"


class HMOAuthViewController: UIViewController {
    
    //声明webView属性
    let webView = UIWebView()
    
    override func loadView() {
        //在loadView阶段 将 根视图 替换为 webView
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavBar()
        loadOauthPage()
    }
    
    //打开授权页面
    private func loadOauthPage() {
        //获取req对象
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string:urlString)!
        let req = NSURLRequest(URL: url)
        webView.loadRequest(req)
    }
    
}


//设置导航条 监听按钮点击事件
extension HMOAuthViewController {
    
    
    //按钮的点击事件
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func testAccount() {
        //使用webView 执行js 字符串
        //js 动态注入
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'onoyomg' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    //完成导航条的设置
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(HMOAuthViewController.close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户", target: self, action: #selector(HMOAuthViewController.testAccount))
    }
    
}


extension HMOAuthViewController: UIWebViewDelegate {
    //使用进度条展示加载进度
    func webViewDidStartLoad(webView: UIWebView) {
        //显示用户等待指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏用户等待指示器
        SVProgressHUD.dismiss()
    }
    
    //授权成功之后 就会回调新页面  在回调页面的地址中会包含code(授权码)
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //打印url
        let urlString = request.URL?.absoluteString ?? ""
        //截取收取成功的字符串中的code
        //定义授权成功的标记
        let successFlag = "code="
        if urlString.containsString(successFlag) {
            //授权成功
            // '!' 表示程序员 确保一定能够找到对应字符串所在位置
            let range = urlString.rangeOfString(successFlag)!
            let code = urlString.substringFromIndex(range.endIndex)
            print(code,urlString)
            
            //获取code 之后 应该使用 code码 请求token(用户访问令牌)
            loadAccessToken(code)
            
            //不加载网页
            return false
        }
        
        return true
    }
    
    
    //使用code 加载用户授权的token(令牌)
    private func loadAccessToken(code: String) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        HMNetworkTools.sharedTools.request(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            print(responseObject,error)
            //请求token成功之后 使用token 和 uid 获取用户信息
            if error != nil {
                SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网")
                return
            }
            
            //请求成功
            self.loadUserInfo(responseObject)
            
        }
    }
    
    //请求用户信息
    private func loadUserInfo(response: AnyObject?) {
        guard let result = response as? [String : AnyObject] else {
            SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网")
            return
        }
        
        let token = result["access_token"]!
        let uid = result["uid"]!
        
        let urlStirng = "https://api.weibo.com/2/users/show.json"
        //字典中可以添加 nil嘛
        let parameters = ["access_token": token, "uid": uid]
        
        HMNetworkTools.sharedTools.request(.GET, urlString: urlStirng, parameters: parameters) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网")
                return
            }
            
            //请求成功
            guard var dict = responseObject as? [String : AnyObject] else {
                SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网")
                return
            }
            
            //用户信息  就应该保存用户信息到本地
            //合并两个字典 统一保存用户数据到本地
            for (key, value) in result {
                dict[key] = value
            }
            
            //使用偏好设置 保存字典数据
            
            
            //1. 将dict 转换为 模型对象
            let user = HMUserAccount(dict: dict)
            //2. 将模型对象转换字典
            let keys = ["access_token","expires_in","uid","name","avatar_large"]
            let userInfo = user.dictionaryWithValuesForKeys(keys)
            print(userInfo)
            //3. 保存字典数据
            let userDefaults = NSUserDefaults.standardUserDefaults()
            //不能够向 偏好设置中保存 nil
            userDefaults.setObject(userInfo, forKey: userInfoKey)
            //同步
            userDefaults.synchronize()
            
            print(NSHomeDirectory())
            
        }
    }
}
